<?php


namespace coco;


use coco\traits\Singleton;

class Config
{
    use Singleton;

    protected $config = [];
    protected $env = null;

    /**
     * @param $name
     * @param null $default
     * @return mixed|null
     */
    public function get($name, $default = null)
    {
        $sub = null;
        if (strpos($name, '.') !== false) {
            list($name, $sub) = explode('.', $name, 2);
        }
        if (!array_key_exists($name, $this->config)) {
            $config_path = App::getInstance()->config_path;
            $new_config = [];
            if (is_file($config_path . $name . '.php')) {
                $new_config = include $config_path . $name . '.php';
            }
            if (is_null($this->env) && is_file(App::getInstance()->app_path . '../.env')) {
                $this->env = parse_ini_file(App::getInstance()->app_path . '../.env', true) ?: [];
            }
            if (!empty($this->env[$name])) {
                foreach ($this->env[$name] as $k => $v) {
                    $new_config[$k] = $v;
                }
            }
            $this->config[$name] = $new_config;
        }
        if (is_null($sub)) {
            return $this->config[$name] ?? $default;
        }
        return $this->config[$name][$sub] ?? $default;
    }

    public function set($name, $value)
    {
        $this->config[$name] = $value;
    }

    public function has($name): bool
    {
        return array_key_exists($name, $this->config);
    }
}